package org.flashbrighton.as3bots.components
{
	import Box2D.Common.Math.b2Vec2;
	import Box2D.Dynamics.b2Body;
	import org.flashbrighton.as3bots.models.BotModel;
	
	public class EngineComponent implements IComponent
	{
		public var maxSpeed:int = 3000;
		
		private var _power:Number;
		private var _PI:Number;
		private var _twoPI:Number;
		
		
		public function EngineComponent()
		{
			_power = 0.0;
			_PI = Math.PI;
			_twoPI = _PI * 2;
		}
		
		
		public function update(botModel:BotModel):void
		{
			setPower(botModel.enginePower);
			move(botModel.body);
			
			// Reset power in case it is not
			// set when this method is called
			_power = 0.0;
		}
		
		
		private function move(body:b2Body):void
		{
			var angle:Number = body.GetAngle();
			angle += _PI;
			angle %= _twoPI;
			if (angle < 0) angle += _twoPI;
			angle -= _PI;
			
			var force:b2Vec2 = new b2Vec2();
			force.x = (_power * maxSpeed) * Math.cos(angle);
			force.y = (_power * maxSpeed) * Math.sin(angle);
			
			body.ApplyForce(force, body.GetWorldCenter());
		}
		
		
		private function setPower(val:Number):void
		{			
			_power = val;
		}

	}
}